import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/common/PrimayButton.dart';
import 'package:magic_car/common/nodata.dart';
import 'package:magic_car/common/showbottomsheet.dart';
import 'package:magic_car/user/anserdetail.dart';
import 'package:magic_car/user/checkstudyinfo.dart';
import 'package:magic_car/user/mytask.dart';
import 'package:magic_car/user/testvideo.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/colors.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_flutter/webview_flutter.dart';
// import 'package:flutter_file_preview/flutter_file_preview.dart';

class TaskdetailPage extends StatefulWidget {
  final String id;
  TaskdetailPage(this.id);
  //TaskdetailPage({Key key, this.id}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.id);
}

class _MyHomePageState extends State<TaskdetailPage> {
  final String id;
  _MyHomePageState(this.id);
  List formList;
  Map info = {'explain': '暂无详情'};

  ScrollController _controller = new ScrollController();
  int page = 1;
  bool end = false;
  String keyword = "";
  var imgsLeng = 0;
  String current_pdf_url;
  File videos;
  bool _saving = false;
  initState() {
    super.initState();

    formList = [];
    loadData();
  }

  //加载数据
  loadData() async {
    setState(() {
      _saving = true;
    });

    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = this.id;

    print(map);

    HttpHelper.post(HttpHelper.API_TaskDetail, (data) async {
      if (data != null) {
        setState(() {
          _saving = false;
          info = data['info'];
        });
        print(data);
      }
    }, params: map);
  }

  //领取任务
  reqtask() async {
    setState(() {
      _saving = true;
    });

    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = this.id;
    map['uid'] = pref.getString('uid');

    print(map);

    HttpHelper.post(HttpHelper.API_ReqTask, (data) async {
      if (data != null) {
        setState(() {
          _saving = false;
        });
        Toast.show(data['msg'], context);
        if (data["code"].toString() == "1") {
          //领取成功
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new MyTaskPage();
          }));
        }
        print(data);
      }
    }, params: map);
  }

  Widget buildImgs(item) {
    List<Widget> tiles = [];

    Widget content;

    List items = item["image_url"];
    print(items.length.toString());

    for (var i = 0; i < items.length; i++) {
      //List temp1 = items[i] as List;
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(5, 0, 0, 10),
        child: GestureDetector(
            onTap: () {
              // print('点击查看图片');
              // Navigator.of(context).push(
              //   NinePicture(items, i),
              // );
            },
            child: Image.network(items[i], width: 100, height: 100)),
      ));
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    if (formList.length > 0) {
      for (var item in formList) {
        tiles.add(Padding(
            padding: new EdgeInsets.fromLTRB(15, 15, 15, 0),
            child: Container(
              decoration: new BoxDecoration(
                color: Colors.white,
              ),
              child: new GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () async {
                    //  Navigator.push(
                    //         context,
                    //         MaterialPageRoute(
                    //             builder: (context) => VideoCompress()));

                    showModalBottomSheet(
                        context: context,
                        builder: (BuildContext context) {
                          return Primaybottomsheet(
                            text: '选择视频来源',
                            confirmPressed: () async {
                              Navigator.pop(context);

                              uploadVideo(1);
                            },
                            confirmtext: '录视频',
                            canceltext: '从相册选取',
                            cancelPressed: () {
                              Navigator.pop(context);

                              uploadVideo(2);
                            },
                          );
                        });
                  },
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: new EdgeInsets.fromLTRB(20, 15, 20, 10),
                        child: Column(
                          children: <Widget>[Text(item["title"])],
                        ),
                      ),
                      Padding(
                        padding: new EdgeInsets.fromLTRB(20, 0, 20, 10),
                        child: Column(
                          children: <Widget>[
                            Text('任务需求：' + item["require_data_des"],
                                style: TextStyle(fontSize: 13))
                          ],
                        ),
                      ),
                      Padding(
                        padding: new EdgeInsets.fromLTRB(20, 0, 20, 10),
                        child: Column(
                          children: <Widget>[
                            Text(
                              '任务奖励：' + item["reward_data_des"],
                              style: TextStyle(fontSize: 13),
                            )
                          ],
                        ),
                      ),
                      // Padding(
                      //   padding: new EdgeInsets.fromLTRB(20, 0, 20, 10),
                      //   child: Row(
                      //     children: <Widget>[
                      //       Text(
                      //         '资料类型：' + item["type_str"],
                      //         style: TextStyle(fontSize: 13),
                      //       ),
                      //       Padding(
                      //           padding: new EdgeInsets.fromLTRB(5, 0, 0, 0),
                      //           child: Image.asset(
                      //               item['cancheck'] == "1"
                      //                   ? 'resource/images/user/unlock.png'
                      //                   : 'resource/images/user/lock.png',
                      //               width: 20,
                      //               height: 15)),
                      //     ],
                      //   ),
                      // ),
                      // item['image_url'].length > 0
                      //     ? Padding(
                      //         padding: new EdgeInsets.fromLTRB(5, 10, 20, 10),
                      //         child: buildImgs(item),
                      //         // child: Row(
                      //         //   children: <Widget>[Text('总试题数：16')],
                      //         // ),
                      //       )
                      //     : new Container(height: 0),
                      Padding(
                        padding: new EdgeInsets.fromLTRB(20, 0, 20, 10),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                                flex: 1,
                                child: Text(
                                  item["starttime"],
                                  style: TextStyle(
                                      color: Color.fromRGBO(153, 153, 153, 1),
                                      fontSize: 13),
                                )),
                          ],
                        ),
                      ),
                    ],
                  )),
            )));
      }
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  uploadVideo(type) async {
    var videofile;

    // if (type == 1) {
    //   videofile = await ImagePicker.pickVideo(source: ImageSource.camera);
    // } else {
    //   videofile = await ImagePicker.pickVideo(source: ImageSource.gallery);
    // }
    // if (videofile == null) return;
    // // File _files = await FlutterNativeImage.compressImage(image.path);
    // File _files = videofile;
    // Map<String, String> map = new Map();

    // HttpHelper.upLoadvideo(_files, (data) {
    //   print(data);
    //   if (data.containsKey('code')) {
    //     Toast.show(data['msg'], context);
    //   } else {}
    // }, params: map);
  }

  Widget build(BuildContext context) {
    return
        // new MaterialApp(
        //     title: '结构件',
        //     home:
        new Scaffold(
            appBar: new AppBar(
              title: new Text(
                '任务详情',
                style: TextStyle(color: Colors.black),
              ),
              backgroundColor: Colors.white,
              elevation: 0,
              // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
            ),
            body: ModalProgressHUD(
                // color: Colors.blue,
                inAsyncCall: _saving,
                child: new Center(
                    child: Container(
                        decoration: new BoxDecoration(
                          color: Color.fromRGBO(238, 238, 238, 1),
                        ),
                        child:
                            // new ListView(children: <Widget>[
                            Stack(
                          children: <Widget>[
                            Align(
                              alignment: Alignment.topCenter,
                              child: Padding(
                                  padding:
                                      new EdgeInsets.fromLTRB(15, 0, 15, 80),
                                  child: ListView(children: <Widget>[
                                    HtmlWidget(info['explain'])
                                    // RichText(text: info['explain'])
                                    // WebView();
                                    // Html(data: info['explain'])
                                  ])),
                            ),
                            Align(
                                alignment: Alignment.bottomCenter,
                                child: Padding(
                                    padding:
                                        new EdgeInsets.fromLTRB(15, 60, 15, 10),
                                    child: PrimayButton(
                                      containercolor:
                                          Color.fromRGBO(238, 238, 238, 1),
                                      text: '去做任务',
                                      width: double.infinity - 30,
                                      height: 40,
                                      textcolor: Colors.white,
                                      bordercolor: Colours.app_main,
                                      colors: Colours.app_main,
                                      borderwidth: 1,
                                      onPressed: () {
                                        reqtask();
                                      },
                                    )))
                          ],
                        )))
                //])))),
                ));
  }

  Future<Null> _onRefresh() async {
    await Future.delayed(Duration(seconds: 3), () {
      print('refresh');
      setState(() {
        page = 1;
      });
      loadData();
    });
  }
}
